<template>
  <div>
    <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    <!-- / 面包屑导航 -->

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区 -->
      <el-alert
        :closable="false"
        title="添加商品信息"
        type="info"
        center
        show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps align-center :active="activeIndex * 1" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs 标点页 -->
      <el-form label-position="top" :rules="addGoodsRules" ref="addGoodsRef" :model="addGoodsForm">
        <el-tabs @tab-click='tadClick' :before-leave="tabsBeforLeave" v-model='activeIndex' tab-position="left">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input type="number" v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品重量">
              <el-input type="number" v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品数量">
              <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品分类">
              <el-cascader
              v-model="addGoodsForm.goods_cat"
              :options="goodsCate"
              :props="addGoodsProps"
              @change="cascaderHandleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox  border v-for="(item, index) in item.attr_vals" :key="index" :label="item"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://liufusong.top:8888/api/private/v1/upload"
              :headers="uploaHeaders"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success='handleSuccess'
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
             <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
             <el-button @click='addGoods' style="margin-top: 20px" type="primary">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- / 卡片视图 -->
    <!-- 点击预览对话框 -->
    <el-dialog :visible.sync="previewdialogVisible"
      width="50%">
      <img style='width: 100%' :src="imgUrl" />
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      activeIndex: 0,
      // 商品列表参数
      addGoodsForm: {
        // 商品名称
        goods_name: '',
        // 价格
        goods_price: 0,
        // 重量
        goods_weight: 0,
        // 数量
        goods_number: 0,
        // 分类
        goods_cat: [],
        // 图片信息
        pics: [
          // {pic:上传图片成功后的地址}
        ],
        goods_introduce: '',
        attrs: []
      },
      // 校验规则
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 级联选择器数据
      goodsCate: [],
      // 级联选择器配置对象
      addGoodsProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      manyData: [],
      onlyData: [],
      uploaHeaders: {
        Authorization: sessionStorage.getItem('token')
      },
      previewdialogVisible: false,
      imgUrl: ''
    }
  },

  created () {
    this.getGoodsCate()
  },
  computed: {
    cateId () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        return null
      }
      return this.addGoodsForm.goods_cat[2]
    }
  },
  methods: {
    // 获取商品分类参数
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      this.goodsCate = res.data
    },
    // 级联选择器发生变化
    cascaderHandleChange () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    tabsBeforLeave (activeName, oldName) {
      if (oldName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级商品分类!')
        return false
      }
    },
    // 获取商品参数
    async getParams (sel) {
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: sel
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败!')
      if (sel === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
        })
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    tadClick () {
      if (this.activeIndex === '1') {
        this.getParams('many')
      } else if (this.activeIndex === '2') {
        this.getParams('only')
      }
    },
    // 点击预览图片
    handlePreview (file) {
      this.previewdialogVisible = true
      this.imgUrl = 'http://liufusong.top:8888/' + file.response.data.tmp_path
    },
    // 点击移除
    handleRemove (file) {
      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 图片上传成功
    handleSuccess (res) {
      this.addGoodsForm.pics.push(
        { pic: res.data.tmp_path }
      )
    },
    addGoods () {
      this.$refs.addGoodsRef.validate(async flag => {
        if (!flag) return this.$message.error('请完善基本信息必填项!')
        // 深拷贝第三总方式：递归拷贝
        // 深拷贝第一总方式
        // const form = JSON.parse(JSON.stringify(this.addGoodsForm))
        // 深拷贝第二总方式
        const form = cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(',') })
        })
        this.onlyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        console.log(form, this.addGoodsForm)
        const { data: res } = await this.$axios.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error('创建失败!')
        this.$message.success('创建成功!')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang='less'>
  .el-steps {
    margin: 20px 0;
  }
  /deep/.el-step__title {
    font-size: 12px;
  }
  .el-checkbox {
    margin-right: 0;
  }
  /deep/.ql-editor {
    height: 400px;
  }
</style>
